<template>
    <el-dialog title="添加权限" v-model="open" width="500">

        <el-form :model="formItem" label-width="auto">
            <el-form-item label="管理员账号">
                <el-input v-model="formItem.account" clearable />
            </el-form-item>
            <el-form-item label="管理员密码">
                <el-input v-model="formItem.password" clearable />
            </el-form-item>
            <el-form-item label="管理员姓名">
                <el-input v-model="formItem.name" clearable />
            </el-form-item>
            <el-form-item label="管理员角色">
                <el-select v-model="formItem.roleId">
                    <el-option v-for="item in roleData.rows" :key="item._id" :label="item.name"
                        :value="item._id"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="open = false">取消</el-button>
            <el-button type="primary" @click="onConfirm">确认</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { addAdminApi, updateAdminApi } from '@/api/admin';
import { useFindData } from '@/composables/findData';
import { ref, watch } from 'vue';

const emit = defineEmits(['findAdmin'])
const open = ref(false);
const formItem = ref<any>({})

const { findRoleAsync, roleData } = useFindData();

watch(open, () => {
    if (open.value) {
        findRoleAsync();
    }
})


function onConfirm() {
    if (formItem.value._id) {
        updateAdmin();
    } else {
        addAdmin();
    }
}

async function addAdmin() {
    const res = await addAdminApi({
        ...formItem.value,
    })
    if (res.code == 200) {
        open.value = false;
        ElMessage.success('管理员数据添加成功');
        emit('findAdmin');
    } else {
        ElMessage.error(res.message);
    }

}
async function updateAdmin() {
    const res = await updateAdminApi({
        ...formItem.value
    })
    if (res.code == 200) {
        open.value = false;
        ElMessage.success('管理员数据修改成功');
        emit('findAdmin');
    } else {
        ElMessage.error(res.message);
    }

}

function openDialog(updateItem?: object) {
    if (updateItem) {
        // 修改
        formItem.value = { ...updateItem }
    } else {
        // 新增
        formItem.value = {};
    }
    open.value = true;
}

defineExpose({
    openDialog
})
</script>

<style scoped></style>